import docsObj from "@/views/Home/hooks/docsObj"
import { objEntries } from "howtools"
import { unref } from "vue"

type Method = 'get' | 'post' | 'put' | 'delete'

interface MethodValue {
    deprecated: boolean,
    description: string,
    operationId: string,
    parameters: unknown[],
    produces: unknown[],
    responses: Record<string, Record<string, any>>,
    security: any,
    sunmmary: string
}

type PathType = Record<string, Record<Method, MethodValue>>

// 通过swagger 接口当中的paths包含的tags，与 tags 当中的 name进行匹配获得某个分类的 url
export function getPathsV2_0(tag: string, paths: PathType) {
    const result: PathType = {}
    for (const url in paths) {
        const pathVal = paths[url]
        const methodsVal = Object.values(pathVal)
        for (const val of methodsVal) {
            const { tags } = val as unknown as { tags: string[] }
            if (tags.indexOf(tag) > -1) {
                result[url] = pathVal
            }
        }
    }
    return result
}


/**
 * @param  {any} requireParams
 * @description 把参数列表解析分离
 */
export function parserParams(requireParams: any) {
    const request: any = {
        query: [],
        path: [],
        header: [],
        body: [],
    }
    function _paramsGetIn(key: "query" | "path" | "header" | "body" | "formData"): unknown[] {
        return requireParams.filter((it: any) => {
            // 修正后端标记一些错误的swagger类型
            if (!["query", "path", "header", "body", "formData"].includes(it.in)) {
                if (it.in === "Integer") {
                    it.type = "integer"
                } else if (it.in === "String") {
                    it.type = "string"
                } else {
                    it.type = "any"
                }
                it.in = "query"
            }
            it.add = false;
            return it.in == key;
        });
    }
    request.query = _paramsGetIn("query") as [];
    request.path = _paramsGetIn("path") as [];
    request.header = _paramsGetIn("header") as [];

    //解析BODY参数
    const body =
        (_paramsGetIn("body") as { schema: { originalRef: any } }[])[0] ||
        {};
    const oref = body.schema ? getOriginRefBySchema(body.schema) : "";

    if (oref) {
        for (const [key, val] of objEntries(unref(docsObj).definitions[oref]?.properties || {})) {
            const k = key as string
            request.body.push({
                name: k,
                ...val
            })
        }
    }

    return request
}

// 解析响应值
export function parserResponse(response: any) {
    if (!response) return []
    const resp: any[] = []
    const rref = response.schema ? getOriginRefBySchema(response.schema) : "";
    let $last_org_ref = "" 
    function _getResponse(resp: any[], $rref: string, isTree = false) {
        $last_org_ref = $rref
        if ($rref) {
            for (const [key, val] of objEntries(unref(docsObj).definitions[$rref]?.properties || {})) {
                const resObj = {
                    name: key,
                    ...val,
                    sub: []
                }

                if (!isTree && val?.items && getOriginRefBySchema(val.items)) {
                    // 如果最后一次ref与上次相同，认定为递归
                    _getResponse(resObj.sub, getOriginRefBySchema(val.items), $last_org_ref == getOriginRefBySchema(val.items))
                }

                if (val && getOriginRefBySchema(val)) {
                    _getResponse(resObj.sub, getOriginRefBySchema(val))
                }
                const k = key as string
                resp.push(resObj)
            }
        }
    }
    _getResponse(resp, rref)
    return resp
}

// 某些定义不存在 OriginRef 参数，需要从$ref当中进行解析， 例如 $ref : "#/definitions/响应信息主体«object»" 解析为 响应信息主体«object»
export function getOriginRefBySchema($schema: any) {
    if ($schema?.originalRef) return $schema.originalRef as string
    return $schema?.$ref?.split("/").pop() as string
}